import Taro from '@tarojs/taro'
import { useEffect, useReducer, useState } from 'react'
import {  View, Navigator } from '@tarojs/components'
import { AtDrawer } from "taro-ui"

import PayChannelOption from './pay-channel'

import './index.scss'
import { useRouter } from '@tarojs/taro'
import { getDeviceApi } from '../../services/Device'
import { chargeApi, queryChargeStatusApi } from '../../services/Charge'
import { PORT_STATUS } from '../../config/Device'
import { hideLoading, reducer, showLoading, showModal, showToast } from '../../utils'
import Bluetooth from './Bluetooth'
import GlobalData from '../../global'
import XImage from '../..//components/XImage'
import ChargeHeader from './chargeHeader'
import ChargeStrategyOption from './chargeStrategyOption'
import XLoadingPage from '../../components/XLoadingPage'
import { Logger } from '../../Logger'

let bluetonth = new Bluetooth()

export default () => {
    const query:any = useRouter().params
    const deviceId = Number(query.deviceId)
    
    let [subTmpId, setsubTmpId] = useState('g_DwiYo5xHLcX_F89mdfGg8d3fMEJiFFBONIJ4fUSNY')

    let [loadingData, dispatchLoadingData] = useReducer(reducer, {
        showLoadingPage : true, //是否显示加载页面
        loadingErrMsg : '',
        loadErr : false //是否请求设备信息出错
    })

    let [queryOrderStatusCount, setqueryOrderStatusCount] = useState(0) //查询充电订单状态次数
    const [formData, formDataDispatch] = useReducer(reducer, {
        portNo : 0,
        selectedPortIndex : -1,
        chargeQuantity : '',
    })

    let [orderId, setOrderId] = useState(0)
    let [chargeSuccess, setchargeSuccess] = useState(false) //是否发起充电成功
    let [deviceConnectStatus, setdeviceConnectStatus] = useState(true) //设备在线状态
    let [portList, setportList] = useState<Port[]>([]) //端口号列表
    let [strategy, setstrategy] = useState<Strategy>() //充电策略

    async function beforeBluetoothCharge() { //蓝牙充电
        //蓝牙充电
        bluetonth.writeBLECharacteristicValue()
    }


    async function charge() {
        // Taro.requestSubscribeMessage({
        //     tmplIds : ['NMqxlnJ2SZYwxn0Rcl-Pw62l7oTThojw0Ij_1YHA5K0', 'P11f1gELgh-3vWQyMPYRWnvUuO12Gon_FLwvPYbF38U'],
        //     success(e) {
        //         console.log('success')
        //         console.log(e)
        //     },
        //     fail(e) {
        //         console.log('取消')
        //         console.log(e)
        //     }
        // })
        // return
        // bluetonth.openBluetoothAdapter()
        // bluetonth.onConnect = () => {

        // }
        // return

        if(formData.selectedPortIndex == -1) {
            showToast('请选择端口')
            return
        }

        if(formData.chargeQuantity === '') {
            showToast('请选择充电金额')
            return
        }

        setqueryOrderStatusCount(0)

        showLoading('请求中')
        let result = await chargeApi({deviceId : deviceId, portNo : formData.portNo, amount : formData.chargeQuantity})
        Logger.info('请求充电结果', result)

        if(!result.success) {
            hideLoading()
            showModal(result.msg)
            return
        }
        setOrderId(result.data)
        queryOrderStatus(result.data)
    }

    function queryOrderStatus(orderId:number) {
        setTimeout(async () => {
            queryOrderStatusCount += 1
            setqueryOrderStatusCount(queryOrderStatusCount)
            let res = await queryChargeStatusApi(orderId)
            if(res.success) {
                let status = res.data
                if(status == 'pending') { //继续查询
                    if(queryOrderStatusCount > 4) {
                        hideLoading()
                        showModal('充电失败，费用稍后将退回')
                        return
                    }
                    //继续查询
                    queryOrderStatus(orderId)
                }else if(status == 'success') {//充电成功
                    hideLoading()
                    Taro.setNavigationBarTitle({
                        title : '充电成功'
                    })
                    GlobalData.chargingCount ++
                    setchargeSuccess(true)

                    Taro.getSetting({
                        withSubscriptions : true,
                        success(res) {
                            console.log(res)
                            if(res.subscriptionsSetting && res.subscriptionsSetting[subTmpId]) {
                                if(res.subscriptionsSetting[subTmpId] == "reject") {
                                    showModal({
                                        content : '请设置消息推送，接收订单信息',
                                        showCancel : false,
                                        success() {
                                            Taro.openSetting({
                                                withSubscriptions : true
                                            })
                                        }
                                    })
                                    
                                }
                            }else {
                                Taro.requestSubscribeMessage({
                                    tmplIds : [subTmpId]
                                })
                            }
                        }
                    })

                }else if(status == 'fail') {
                    hideLoading()
                    showModal('充电失败，费用稍后将退回')
                }
            }else {
                hideLoading()
                showModal(res.msg)
            }
        }, 5000);
        
    }


    async function initData() {
        let data = await getDeviceApi(deviceId) //获取设备信息
        if(data) {
            if(data.portList) {
                setportList(data.portList) //设备端口
            }
            if(data.strategy) {
                setstrategy(data.strategy) //设备端口
            }
            dispatchLoadingData({showLoadingPage : false})
        }else {
            dispatchLoadingData({loadErr : true, loadingErrMsg : '查询设备信息失败'})
        }
    }


    


    useEffect(() => {
        //bluetonth.setDeviceNo(deviceNo)
        initData() //获取设备信息
    }, [])


    

    return (
        <>
            <View className='page-view'>
                {deviceConnectStatus == false &&
                    <View className='device-offline'>设备已掉线，请开启蓝牙充电</View>
                }
                
                <View className='flex-1' style='overflow-y:auto'>
                    <>
                        <ChargeHeader strategy={strategy} />
                        <View className='blank'></View>
                        <View className='p-l-r m-t-30'>
                            <View className='f-32'>选择充电插座</View>
                            <View className='port-option-list m-t-20'>
                                {
                                    portList.map((port:any, index:number) => {
                                        let optionClass = 'port-option'
                
                                        let statusClass = 'port-status'
                                        if(port.status == 0) {
                                            statusClass += ' free'
                                        }else {
                                            optionClass += ' disabled'
                                            if(port.status == 1) {
                                                statusClass += ' charging'
                                            }
                                            
                                        }

                                        if(formData.selectedPortIndex == index) {
                                            optionClass += ' selected'
                                        }

                                        return (
                                            <View onClick={() => { if(port.status == 0) formDataDispatch({selectedPortIndex : index, portNo : port.portNo}) }}>
                                                <View className={optionClass}>
                                                    <View className='wrap xy'>{port.portNo}</View>
                                                </View>
                                                <View className={statusClass}>{PORT_STATUS[port.status] || '不可用'}</View>
                                            </View>
                                        )
                                    })
                                }
                            </View>
                        </View>

                        <View className='blank m-t-30'></View>
                        <View className='p-l-r m-t-30'>
                            <View className='f-32'>选择充电金额</View>
                            {strategy &&
                                <View className='m-t-20'>
                                    <ChargeStrategyOption options={strategy.options} price={strategy.unitPrice} onChange={e => formDataDispatch({chargeQuantity : e})}></ChargeStrategyOption>
                                </View>
                            }
                        </View>

                        <View className='blank m-t-30'></View>
                        <View className='p-l-r m-t-30'>
                            <View className='f-32'>支付方式：</View>
                            <View className='m-t-10'>
                                <PayChannelOption onChange={() => {}}></PayChannelOption>
                            </View>
                        </View>
                        <View className='blank m-t-30'></View>
                    </>
                </View>

                <View className='footer-nav'>
                    <View className='amount font-bold p-l'>需支付：{formData.chargeQuantity || 0}元</View>
                    <View className='confirm-button' onClick={charge}>{deviceConnectStatus ? '立即充电' : '开启蓝牙充电'}</View>
                </View>

            </View>

            <AtDrawer show={chargeSuccess} right mask width='100%'>
                    <View className='absolute xy'>
                        <View className='text-center'>
                            <XImage className='success-image' src='charge-sucess.png'></XImage>
                            <View className='m-t-60'>
                                <Navigator className='btn' openType='redirect' url='/pages/home/index'>返回首页</Navigator>
                                <Navigator className='btn primary m-l-30' openType='redirect' url={'/userClient/pages/charging/index?from=charge&orderId=' + orderId}>查看订单</Navigator>
                            </View>
                        </View>
                    </View>
            </AtDrawer>

            {loadingData.showLoadingPage &&
                <XLoadingPage loading={!loadingData.loadErr}>
                    <View className='text-center'>{loadingData.loadingErrMsg}</View>
                </XLoadingPage>
            }
                        
        </>
    )
}